<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="订单编号" prop="orderNo">
              <el-input v-model="queryParams.orderNo" placeholder="请输入订单编号" clearable @keyup.enter="handleQuery"
                style="width: 150px;" />
            </el-form-item>
            <el-form-item label="客户名称" prop="customerName">
              <el-input v-model="queryParams.customerName" placeholder="请输入客户名称" clearable @keyup.enter="handleQuery"
                style="width: 150px;" />
            </el-form-item>
            <el-form-item label="订单类型" prop="orderType">
              <el-select v-model="queryParams.orderType" placeholder="请选择订单类型" clearable @keyup.enter="handleQuery"
                style="width: 150px;">
                <el-option label="发货单" value="DELIVERY" />
                <el-option label="进货单" value="PURCHASE" />
                <el-option label="报价单" value="QUOTATION" />
                <el-option label="销售单" value="SALES" />
                <el-option label="采购单" value="PROCUREMENT" />
                <el-option label="对账单" value="STATEMENT" />
                <el-option label="退货单" value="RETURN" />
                <el-option label="物流单" value="LOGISTICS" />
              </el-select>
            </el-form-item>
           
            <!-- 开始时间结束时间 -->
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker v-model="queryParams.startTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择开始时间" style="width: 150px;" />
            </el-form-item>
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker v-model="queryParams.endTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss" placeholder="请选择结束时间"
                style="width: 150px;" />
            </el-form-item>
             <el-form-item label="状态" prop="isCancel">
              <el-select v-model="queryParams.isCancel" placeholder="请选择状态" clearable @keyup.enter="handleQuery" style="width: 150px;">
                <el-option label="正常" value="Y" />
                <el-option label="作废" value="N" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <!-- <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:order:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['system:order:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['system:order:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:order:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template> -->

      <el-table v-loading="loading" border :data="orderList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="编号" align="center" prop="orderNo" />
        <el-table-column label="客户名称" align="center" prop="customerName" />
        <el-table-column label="类型" align="center" prop="orderType.info" />
        <el-table-column label="金额" align="center" prop="amount" />
        <el-table-column label="客户类型" align="center" prop="customerType.info" />
        <el-table-column label="开单人" align="center" prop="creatorName" />
        <el-table-column label="创建时间" align="center" prop="createTime" />
        <!-- 是否作废 -->
        <el-table-column prop="isCancel" label="订单状态" align="center">
          <template #default="scope">
            <dict-tag :options="is_cancel" :value="scope.row.isCancel?.code" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width" width="160">
          <template #default="scope">
            <el-button link type="primary" @click="goDetail(scope.row)">详情</el-button>
            <el-button link type="danger" @click="handleCancel(scope.row)"
              v-if="scope.row.isCancel?.code === 'Y'">作废</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total-amount="totalActualAmount" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

  </div>
</template>

<script setup name="Order" lang="ts">
import { myOrderList, getOrder, delOrder, addOrder, updateOrder ,cancelOrder } from '@/api/order';
import { OrderVO, OrderQuery, OrderForm } from '@/api/order/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { is_cancel } = toRefs<any>(proxy?.useDict('is_cancel'));

const orderList = ref<OrderVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const totalActualAmount = ref(0);

const queryFormRef = ref<ElFormInstance>();
const orderFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: OrderForm = {
  id: undefined,
  orderNo: undefined,
  orderType: undefined,
  amount: undefined,
  discountAmount: undefined,
  actualAmount: undefined,
  settleStatus: undefined,
  voucherImgs: undefined,
  signature: undefined,
  remark: undefined,
  tagId: undefined,
  addressId: undefined,
  customerId: undefined,
  customerName: undefined,
  customerContactName: undefined,
  customerPhone: undefined,
  customerAddress: undefined,
  customerType: undefined,
  companyId: undefined,
  companyName: undefined,
  companyContactName: undefined,
  companyAddress: undefined,
  companyPhone: undefined,
  creatorId: undefined
};
const data = reactive<PageData<OrderForm, OrderQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNo: undefined,
    orderType: undefined,
    amount: undefined,
    discountAmount: undefined,
    actualAmount: undefined,
    settleStatus: undefined,
    voucherImgs: undefined,
    signature: undefined,
    tagId: undefined,
    addressId: undefined,
    customerId: undefined,
    customerName: undefined,
    customerContactName: undefined,
    customerPhone: undefined,
    customerAddress: undefined,
    customerType: undefined,
    companyId: undefined,
    companyName: undefined,
    companyContactName: undefined,
    companyAddress: undefined,
    companyPhone: undefined,
    creatorId: undefined,
    params: {},
    startTime: undefined,
    endTime: undefined
  },
  rules: {
    id: [{ required: true, message: '订单唯一ID不能为空', trigger: 'blur' }],
    orderNo: [{ required: true, message: '订单编号不能为空', trigger: 'blur' }],
    orderType: [
      {
        required: true,
        message: '订单类型：1-发货单，2-进货单，3-报价单，4-销售单，5-采购单，6-对账单，7-退货单，8-物流单不能为空',
        trigger: 'change'
      }
    ],
    amount: [{ required: true, message: '应收/应付金额不能为空', trigger: 'blur' }],
    discountAmount: [{ required: true, message: '优惠金额不能为空', trigger: 'blur' }],
    actualAmount: [{ required: true, message: '实收/实付金额不能为空', trigger: 'blur' }],
    settleStatus: [{ required: true, message: '结算状态：1-未结，2-部分结，3-结清不能为空', trigger: 'change' }],
    companyId: [{ required: true, message: '开单方主体ID不能为空', trigger: 'blur' }],
    creatorId: [{ required: true, message: '开单人ID不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询订单主（客户ID和供应商ID必须二选一，由应用程序保证）列表 */
const getList = async () => {
  loading.value = true;
  const res = await myOrderList(queryParams.value);
  orderList.value = res.rows;
  total.value = res.total;
  totalActualAmount.value = res.totalActualAmount;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  orderFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 作废按钮操作 */
const handleCancel = async (row: OrderVO) => {
  await proxy?.$modal
    .confirm('是否确认作废编号为"' + row.orderNo + '"的数据项？')
    .finally(() => (loading.value = false));
  await cancelOrder(row.id);
  proxy?.$modal.msgSuccess('作废成功');
  await getList();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: OrderVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

// 跳转详情
const router = useRouter();
const goDetail = (row: OrderVO) => {
  if (!row?.id) return;
  router.push({ path: '/order/detail', query: { id: row.id } });
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加订单主（客户ID和供应商ID必须二选一，由应用程序保证）';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: OrderVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getOrder(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改订单主（客户ID和供应商ID必须二选一，由应用程序保证）';
};

/** 提交按钮 */
const submitForm = () => {
  orderFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateOrder(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addOrder(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: OrderVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal
    .confirm('是否确认删除订单主（客户ID和供应商ID必须二选一，由应用程序保证）编号为"' + _ids + '"的数据项？')
    .finally(() => (loading.value = false));
  await delOrder(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/order/export',
    {
      ...queryParams.value
    },
    `order_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>
